import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler


# 设置多项式项目的
# 为变量添加阶数（阶数过多会产生过拟合，二阶数过小会产生欠拟合）
# 能够使函数曲线更好的拟合数据集

x = np.random.uniform(-3, 3, size=100)
X = x.reshape(-1, 1)
y =  0.5 * x * x + 3 * x + np.random.normal(0, 1 , 100)


# 普通写法
# ploy_f = PolynomialFeatures(degree=2)
# ploy_f.fit(X)
# X2 = ploy_f.transform(X)
#
# line_re = LinearRegression()
# line_re.fit(X2, y)
# y_predict = line_re.predict(X2)

# pipleLine 写法
pip = Pipeline({
    ("ployFeature", PolynomialFeatures(degree=2)),
    ("std_scaler", StandardScaler()),
    ("lin_reg", LinearRegression())
})

pip.fit(X, y)
y_predict2 = pip.predict(X)

# plt.plot(np.sort(x), y_predict[np.argsort(x)], color="red")
plt.plot(np.sort(x), y_predict2[np.argsort(x)], color="green")
plt.scatter(x, y)
plt.show()
